import { useMount } from "ahooks";
import { Form, Input, Table, TableProps } from "antd";
import { FormInstance } from "rc-field-form";
import React from "react";

import "./index.less";

const EditableCell = ({
  editing,
  dataIndex,
  title,
  inputType,
  record,
  index,
  children,
  disabled,
  ...restProps
}: any) => {
  return (
    <td {...restProps}>
      {editing ? (
        <Form.Item
          name={dataIndex}
          style={{
            margin: 0,
          }}
          rules={[
            {
              required: true,
              message: ``,
            },
          ]}
        >
          <Input disabled={disabled} />
        </Form.Item>
      ) : (
        children
      )}
    </td>
  );
};

interface EditableTableProps<RecordType> extends TableProps<RecordType> {
  editingKey?: string;
  onLoad?: (form: FormInstance<any>) => void;
}

const EditableTable: React.FC<EditableTableProps<any>> = ({
  dataSource,
  columns,
  editingKey,
  onLoad,
  ...props
}) => {
  const [form] = Form.useForm();
  const isEditing = (record: any) => record.key === editingKey;
  const mergedColumns = columns?.map((col: any) => {
    if (!col.editable) {
      return col;
    }

    return {
      ...col,
      onCell: (record: any) => ({
        record,
        dataIndex: col.dataIndex,
        title: col.title,
        editing: isEditing(record),
        disabled: col.disabled && col.disabled(record, col),
      }),
    };
  });

  useMount(() => {
    onLoad && onLoad(form);
  });

  return (
    <Form form={form} component={false}>
      <Table
        {...props}
        components={{
          body: {
            cell: EditableCell,
          },
        }}
        className="ra-editable-table"
        bordered
        dataSource={dataSource}
        columns={mergedColumns}
        rowClassName="editable-row"
        pagination={false}
      />
    </Form>
  );
};

export default EditableTable;
